#!/usr/bin/env python3

# Copyright (c) 2022 PAL Robotics S.L. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

import em

from tiago_description.tiago_launch_utils import get_tiago_hw_suffix

em_file_path = sys.argv[1]

no_em_extension_path = os.path.splitext(em_file_path)[0]
no_extension_path = os.path.splitext(no_em_extension_path)[0]
extension = os.path.splitext(no_em_extension_path)[1]

for arm in ['tiago-arm', 'no-arm']:
    if arm not in ['no-arm']:
        end_effectors = ['pal-hey5', 'pal-gripper', 'no-ee', 'robotiq-2f-85',
                         'robotiq-2f-140', 'robotiq-epick', 'custom']
    else:
        end_effectors = ['no-ee']
    for end_effector in end_effectors:
        cfg = {
            'has_arm': arm not in ['no-arm'],
            'end_effector': end_effector,
        }
        with open(em_file_path, 'r') as f:
            expanded_contents = em.expand(f.read(), cfg)

        suffix = get_tiago_hw_suffix(arm=arm, end_effector=end_effector)

        expanded_file_name = no_extension_path + suffix + extension
        with open(expanded_file_name, 'w') as f:
            msg = "Autogenerated file, don't edit this, edit {} instead".format(
                os.path.basename(em_file_path))
            if extension == '.yaml':
                f.write('#' + msg + '\n')
            elif extension in ['.xacro', '.xml']:
                f.write('<!-- ' + msg + '-->\n')

            f.write(expanded_contents)
        print('Generated ' + expanded_file_name)
